<template>
  <div class="comment-container">
      <h4>发表评论</h4>
      <hr>
      <textarea placeholder="请输入要评论的内容" maxlength="150" v-model="msg"></textarea>
      <mt-button type="primary" size="large" @click="getContent">发表评论</mt-button>

      <div class="comment-list" v-for="(item ,i) in comments" :key="item.add_time">
          <div class="comment-item">
              <div class="comment-title">第{{i+1}}楼 &nbsp;&nbsp;用户：{{item.user_name}}&nbsp;&nbsp;发表时间：{{item.add_time | dateFormat("YYYY-MM-DD")}}</div>
              <div class="comment-conent">
                  {{item.content}}
              </div>
          </div>
      </div>
      <mt-button type="danger" size="large" plain @click="getmore">加载更多</mt-button>

  </div>
</template>

<script>
import {Toast} from 'mint-ui'

export default {
    data(){
        return {
            pageindex:1,//默认展示第一页的数据
           comments:[], //存放评论数组
            msg:""//评论内容
        }
    },
    created(){
        this.getcomments()
    },
    
    methods:{
        getcomments(){//根据 页码获取当前评论数据
            this.$http.get("api/getcomments/"+this.id+"?pageindex="+this.pageindex).then(result =>{
                if(result.body.status===0){
                   // console.log(result.body.message)
                   //this.comments=result.body.message
                   this.comments=this.comments.concat(result.body.message)
                }else{
                    Toast("评论列表获取失败")
                }
            })

            
        },
        getmore(){//获取更多评论
            this.pageindex++;
            this.getcomments();

        },
        getContent(){//点击提交评论
            if(this.msg.trim().length<=0){
                return Toast("评论内容不能为空")
            }
            //post请求参数：地址，数据对象，提交格式
            this.$http.post("api/postcomment/"+this.id,{content:this.msg.trim()}).then(result => {
                //console.log(result.body)
                if(result.body.status===0){
                    //添加最新评论内容
                    this.comments.unshift({ 
                        user_name:"匿名用户",
                        add_time:Date.now(),
                        content:this.msg 
                    })
                    this.msg =""
                }else{
                   Toast("评论失败") 
                }
            })
            
        }
        
    },
    props:["id"]//存放父组件传递过来的值
  
}
</script>

<style lang="less" scoped>
.comment-container{
    textarea{
        margin: 0;
        font-size: 14px;
    }
    .comment-list{
        .comment-item{
            font-size: 14px;
            .comment-title{
                background-color: #ccc;
                line-height:30px;
            }
            .comment-conent{
                line-height: 35px;
                text-indent: 2em;
            }
        }
    }
}
</style>
